﻿using System;
using System.Collections.Generic;
using System.Security.Claims;
using System.Text;
using System.Linq;
using JWT.Algorithms;
using JWT;
using JWT.Serializers;

namespace Exhort.Utility.Helper
{
    /// <summary>
    /// JWT认证
    /// </summary>
    public class JwtAuthHelper
    {
        //加解密Secret
        public static readonly string Secret = ConfigHelper.GetByKey("jwtToken:secret");

        //过期时间 （单位：分钟）
        public static readonly int Expiration = Convert.ToInt32(ConfigHelper.GetByKey("jwtToken:expiration"));

        /// <summary>
        /// JWT加密算法
        /// </summary>
        /// <param name="payload">负荷部分，存储使用的信息</param>
        /// <param name="secret">密钥</param>
        /// <returns></returns>
        public static string BuildToken(IDictionary<string, object> payload)
        {
            var provider = new UtcDateTimeProvider();

            var secondsSinceEpoch = UnixEpoch.GetSecondsSince(provider.GetNow().AddMinutes(Expiration));

            payload.Add("exp", secondsSinceEpoch);

            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

            return encoder.Encode(payload, Secret);
        }

        /// <summary>
        /// JWT解密算法
        /// </summary>
        /// <param name="token">需要解密的token串</param>
        /// <param name="secret">密钥</param>
        /// <returns></returns>
        public static IDictionary<string, object> DecodeToken(string token)
        {
            try
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                var provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);

                return decoder.DecodeToObject<IDictionary<string, object>>(token, Secret, verify: true);
            }
            catch { }

            return null;
        }
    }
}
